package org.goj.common.execption;

import cn.hutool.core.text.StrBuilder;
import org.goj.common.model.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author CK
 * @date 2020/10/11 11:17
 */
@ControllerAdvice
public class GlobalException {

    /**
     * 数据校验异常处理
     *
     * @param e 异常对象
     * @return Result<String>
     * @author CK
     * @date 2021/3/25 9:53
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        StrBuilder errorMsg = new StrBuilder();
        for (FieldError error : errors) {
            errorMsg.append("[");
            errorMsg.append(error.getDefaultMessage());
            errorMsg.append("]\n");
        }
        return Result.failed(Objects.requireNonNull(errorMsg.toString()));
    }

    /**
     * 全局异常处理
     *
     * @param e 1
     * @return Result<String>
     * @author CK
     * @date 2020/9/30 10:22
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> error(Exception e) {
        e.printStackTrace();
        return Result.failed(e.getMessage());
    }

}
